import Taro from "@tarojs/taro";
import Api from "./Api";
import { get } from "lodash";
import utils from "src/utils/utils";
// import uploadOssClient from "./uploadOssClient";
// import imageseg20191230 from '@alicloud/imageseg20191230';
// import OpenApi from '@alicloud/openapi-client';
// import Util from '@alicloud/tea-util';
// import * as $tea from '@alicloud/tea-typescript';

class UtilsApi extends Api {

    constructor() {
        super();
    }

    // 1. 通用抠图
    async commonCutImage(imageUrl: string) {

        const res = await this._from('/common/ai/commonSeg', { imageUrl });
        if (res.code !== 200) {
            Taro.showToast({
                title: '图片不符合要求',
                icon: 'none'
            });
            throw new Error("通用抠图失败");
        }
        let imageURL = get(res, "data.body.data.imageURL");
        imageURL = imageURL.replace(/^https?/, 'https');
        console.log("imageURL", imageURL);
        return imageURL;
    }

    //人体分割
    async humanBodySeg(imageUrl: string) {
        const res = await this._from('/common/ai/humanBodySeg', { imageUrl });
        if (res.code !== 200) {
            Taro.showToast({
                title: '图片不符合要求',
                icon: 'none'
            });
            throw new Error("人体分割失败");
        }
        let imageURL = get(res, "data.body.data.imageURL");
        imageURL = imageURL.replace(/^https?/, 'https');
        console.log("imageURL", imageURL);
        return imageURL;
    }

    //头像分割
    async iconSeg(imageUrl: string): Promise<Array<string>> {
        const res = await this._from('/common/ai/iconSeg', { imageUrl });
        if (res.code !== 200) {
            Taro.showToast({
                title: '图片不符合要求',
                icon: 'none'
            });
            throw new Error("头像分割失败");
        }
        let imageURLs = get(res, "data.body.data.elements").map((item) => {
            return item.imageURL.replace(/^https?/, 'https');
        });
        // [0].imageURL");
        // imageURL = imageURL.replace(/^https?/, 'https');
        console.log("imageURLs", imageURLs);
        return imageURLs;
    }

    //人像动漫化
    async humanAnimeStyle(imageUrl: string) {
        const res = await this._from('/common/ai/humanAnimeStyle', { imageUrl });
        if (res.code !== 200) {
            Taro.showToast({
                title: '图片不符合要求',
                icon: 'none'
            });
            throw new Error("人像动漫化失败");
        }
        let imageURL = get(res, "data.body.data.imageURL");
        imageURL = imageURL.replace(/^https?/, 'https');
        console.log("imageURL", imageURL);
        return imageURL;
    }

    // ai生图
    async aiImage(prompt: string): Promise<string> {
        const res = await this._post('/common/textToImage/generate', { prompt });
        console.log("res", res);
        if (res.code === 200) {
            const url = get(res, "data.output.results[0].url");

            if (!url) {
                return "";
            }

            const ossUrl = await new Promise<string>((resolve, reject) => {
                Taro.downloadFile({
                    url: url,
                    success: async (res) => {
                        if (res.statusCode === 200) {
                            const uploadedUrl = await utilsApi.uploadOss(res.tempFilePath, Api.ossDirectory);
                            console.log('上传后的 URL:', uploadedUrl);
                            const ossUrl = utils.ossSuffix(uploadedUrl, 1024, false);
                            resolve(ossUrl);
                        }
                    },
                    fail: (err) => {
                        resolve("");
                    }
                });
            });

            console.log("ossUrl", ossUrl);
            return ossUrl;
        } else {
            Taro.showToast({
                title: res.msg,
                icon: 'none'
            });
            return "";
        }
    }

    // 查询某title字典枚举值
    async queryPropertyByTitle(title: string) {
        const res = await this._get("/baseProperty/queryPropertyByTitle", { title });
        let detail = get(res, "data.detail");
        try {
            detail = JSON.parse(detail);
        } catch (error) { }
        return detail;
    }

    // 获取图片信息
    getImageSize(tempFilePath) {
        return new Promise<Taro.getImageInfo.SuccessCallbackResult>((resolve, reject) => {
            Taro.getImageInfo({
                src: tempFilePath,
                success: (res) => {
                    resolve(res);
                },
                fail: (err) => {
                    Taro.showToast({
                        title: '获取图片信息失败',
                        icon: 'none'
                    });
                }
            });
        });
    }

    ossConfig;

    // 2. 获取OSS配置信息（需自行实现服务端接口）
    async getOSSToken() {
        const res = await this._post('/common/oss/getOssUploadToken');
        if (!res.data) {
            throw new Error("获取OSS上传信息失败");
        }
        return res.data; // 返回结构应包含 policy, signature, accessid 等信息
    }

    parseXML(xmlString: string) {
        const result: any = {};
        // 提取标签内容的正则表达式
        const tagRegex = /<([^>]+)>([^<]*)<\/\1>/g;
        let match;

        while ((match = tagRegex.exec(xmlString)) !== null) {
            const tagName = match[1];
            const tagValue = match[2];
            result[tagName] = tagValue;
        }

        return result;
    }

    // 上传文件到阿里云oss
    async uploadOss(filePath: string, dir: string, tryNUm = 0): Promise<string> {
        // 获取OSS配置
        const ossConfig = await this.getOSSToken();
        const imgSize = await this.getImageSize(filePath);
        const { width, height, type, } = imgSize;
        const fileName = `${width}_${height}_${new Date().valueOf()}.${type}`;
        return new Promise<string>((resolve, reject) => {
            let {
                host, policy, security_token, signature,
                version, x_oss_credential, x_oss_date,
            } = ossConfig;
            // 需要https
            host = host.replace(/^https?/, 'https');
            Taro.uploadFile({
                url: host, // OSS访问域名
                filePath: filePath, // 图片的本地临时路径
                name: "file", // 文件字段名
                formData: {
                    key: `${dir}/${fileName}`,  //上传文件名称
                    policy: policy,   //表单域
                    'x-oss-signature-version': version,    //指定签名的版本和算法
                    'x-oss-credential': x_oss_credential,   //指明派生密钥的参数集
                    'x-oss-date': x_oss_date,   //请求的时间
                    'x-oss-signature': signature,   //签名认证描述信息
                    'x-oss-security-token': security_token,  //安全令牌
                    success_action_status: "200"  //上传成功后响应状态码
                },
                success: (res) => {
                    // console.log(`上传${res.statusCode === 200 ? "成功" : "失败"}`, res);
                    if (res.data) {
                        const resXML = this.parseXML(res.data);
                        console.log("RequestId", resXML.RequestId);
                    }

                    if (res && res.data && res.data.includes("EntityTooLarge")) {
                        Taro.showToast({
                            title: '图片过大，请重新选择',
                            icon: 'none'
                        });
                        Taro.hideLoading();
                        return;
                    }
                    // 成功状态才
                    if (res.statusCode !== 200) {
                        Taro.hideLoading();
                        throw new Error("上传失败");
                    }
                    resolve(`/${dir}/${fileName}`);
                },
                fail: (err) => {
                    if (tryNUm < 2) { // 重试次数
                        setTimeout(() => {
                            this.uploadOss(filePath, dir, tryNUm + 1).then(resolve)
                        }, 500);
                    } else {
                        Taro.hideLoading();
                        Taro.showToast({
                            title: '上传失败',
                            icon: 'none'
                        });
                    }
                }
            });
        });
    }

    // 从URL解析文件类型
    getMimeTypeFromUrl(url) {
        const extension = url.split('.').pop().toLowerCase();
        const typeMap = {
            jpg: 'image/jpeg',
            jpeg: 'image/jpeg',
            png: 'image/png',
            gif: 'image/gif',
            webp: 'image/webp'
        };
        return typeMap[extension] || 'image/jpeg'; // 默认jpeg格式
    }

    urlToBase64(url) {
        return new Promise((resolve, reject) => {
            // 步骤1：下载图片到临时路径
            Taro.downloadFile({
                url: url.replace(/^https?/, 'https'),
                success: (downloadRes) => {
                    if (downloadRes.statusCode !== 200) {
                        reject('下载失败:' + downloadRes.errMsg);
                        return;
                    }

                    // 步骤2：解析图片格式
                    const mimeType = this.getMimeTypeFromUrl(url);

                    // 步骤3：读取文件内容
                    const fs = Taro.getFileSystemManager(); // 修改为 Taro.getFileSystemManager()

                    fs.readFile({
                        filePath: downloadRes.tempFilePath,
                        encoding: 'base64',
                        success: (readRes) => {
                            resolve(`data:${mimeType};base64,${readRes.data}`);
                        },
                        fail: (readErr) => {
                            reject('读取失败:' + readErr.errMsg);
                        }
                    });
                },
                fail: (err) => {
                    reject('下载失败:' + err.errMsg);
                }
            });
        });
    }


    //ai的剩余使用次数
    aiUseCount = 0;
    updateAiUseCount(type) { //: "kouTu" | "dongMa" | "tuYa" | "xuanRan" = "kouTu") {
        return this._get("/member/member-use-count/queryUseCountResult", { type });
    }

}


const utilsApi = new UtilsApi();

export default utilsApi;